﻿using WheelClean2.Model;
using imcactivex_x64Lib;
using System.Collections.Generic;
using System.Threading;

namespace WheelClean2.Mould
{
    /// <summary>
    /// 用于和达标板卡进行通讯
    /// </summary>
    public  class DaBiaoHelper
    {



        /// <summary>
        /// 主体板卡 用于提供基本的方法
        /// </summary>
        public IIMCAX64Mark Mark;

        /// <summary>
        /// 多卡控制
        /// </summary>
        public IIMCAX64MultiSystem MultiSystem;
        /// <summary>
        /// 链接的板卡集合
        /// </summary>
        public List<MarkInfo> Marks;

        public  string Status = "板卡未链接";

        //单例模式确保全局只有一个
        private static DaBiaoHelper _instance;

        public static DaBiaoHelper Instance
        {
            get
            {
                _instance ??= new DaBiaoHelper();
                return _instance;
            }
        }

        private DaBiaoHelper()
        {
            //方法主体初始化
            Mark = new IMCAX64MarkClass();
            Mark.Initial(0);
            //多卡控制初始化
            MultiSystem = new IMCAX64MultiSystemClass();
            MultiSystem.Initial();
            Marks = new List<MarkInfo>();
        }


        /// <summary>
        /// 多卡初始化
        /// </summary>
        public void MultiInit()
        {
            Thread thread = new Thread(() =>
            {

                int count = CountControlCards();
                List<CardInfo> cardInfoList = new List<CardInfo>();
                while (cardInfoList.Count != 2 || (cardInfoList[0].CardId == cardInfoList[1].CardId))
                {
                    cardInfoList.Clear();   
                    for (int i = 0; i < CountControlCards(); i++)
                    {
                        cardInfoList.Add(GetControlCardInfo(i + 1));
                        Thread.Sleep(500);
                    }
                    Status = "板卡正在链接";
                }
                cardInfoList.ForEach(t => Marks.Add(new MarkInfo(this, t)));
                Status = "板卡已链接";
            });
            thread.Start();
        }

        /// <summary>
        /// 取得能连线打标卡的数量
        /// </summary>
        /// <returns></returns>
        public int CountControlCards()
        {
            return Mark.CountControlCards();
        }

        public CardInfo GetControlCardInfo(int index)
        {
            CardInfo cardInfo = new CardInfo();
            Mark.GetControlCardInfo(index,ref cardInfo.channelType, ref cardInfo.locked, ref cardInfo.cardIp, ref cardInfo.lockUnlockHostIp,
                ref cardInfo.cardId);
            return cardInfo;
        }

        public int CreateSystem(string cardId, string folderName)
        {
            int errorCode = 0;
           
            return MultiSystem.CreateSystem($"@{cardId}@", folderName, errorCode); 
        }



    }
}
